<?php

namespace App\Console\Commands;

use App\Models\SafePlan;
use App\Models\SafePlanOrder;
use Illuminate\Console\Command;

class RefreshOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'refreshSafePlanOrder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $since = urlencode(date('Y-m-d', time() - 86400).' 00:00:00');
        $nodes = SafePlan::where('feedback_api', '!=', '')->get();

        foreach($nodes as $node)
        {
            $url = $node->feedback_api;
            if(empty(parse_url($url)['query']))
            {
                $url = $url."?since={$since}";
            }else
            {
                $url = $url."&since={$since}";
            }

            $content = file_get_contents($url);

            $data = json_decode($content, true);

            if($data['status'] != 0 )
            {
                continue;
            }
            foreach($data['data'] as $v)
            {
                $tmp = [];
                $order = new SafePlanOrder();
                $tmp = array_only($v, [
                    'sn',
                    'name',
                    'id_card',
                    'email',
                    'phone',
                    'safe_name',
                    'safe_number',
                    'price',
                    'buy_date',
                    'insurance_no',
                ]);
                $tmp['others'] = json_encode($v);
                $tmp['id_card'] = $v['idcard'];
                $this->_rmNullVal($tmp);
                $order->fill($tmp)->save();
            }

        }
    }

    private function _rmNullVal(&$data)
    {
        foreach($data as $key=>$value)
        {
            if($value == null)
            {
                unset($data[$key]);
            }
        }
    }
}
